package controler;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.GetCnn;

import model.SanphamModel;

/**
 * Servlet implementation class quanlydanhmuc
 */
@WebServlet("/quanlydanhmuc")
public class quanlydanhmuc extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public quanlydanhmuc() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @throws SQLException 
	 * @throws IOException 
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException{
    	String tendanhmuc = request.getParameter("tendanhmuc");
    	tendanhmuc = new String(tendanhmuc.getBytes("8859_1"),"UTF8");
    	Connection cnn = GetCnn.getCnn();
		Statement stat = cnn.createStatement();
    	String option = request.getParameter("option");
    	int madanhmuc = 0;
    	String sSQL = "";
    	if(option.equals("addnew")){
    		SanphamModel model = new SanphamModel();
    		madanhmuc = model.getTotalRows("select * from DANHMUC")+1;
    		sSQL ="insert into DANHMUC(MADANHMUC,TENDANHMUC) values('"+madanhmuc+"',N'"+tendanhmuc+"')";
    		stat.executeUpdate(sSQL);
    	}
    	if(option.equals("edit")){
    		sSQL = "update DANHMUC set TENDANHMUC =N'"+tendanhmuc+"' where MADANHMUC = '"+request.getParameter("madanhmuc")+"'";
    		stat.executeUpdate(sSQL);
    	}
    	response.sendRedirect("admindanhmuc");
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			processRequest(request,response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			processRequest(request,response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
